package com.decent.ejfadmin.order.service.impl;


import com.decent.ejfadmin.collectcard.service.CollectCardDetailService;
import com.decent.ejfadmin.common.bean.ExkSupplyCard;
import com.decent.ejfadmin.common.bean.SupplyCard;
import com.decent.ejfadmin.common.bean.SupplyConsumption;
import com.decent.ejfadmin.common.enums.SupplyCardError;
import com.decent.ejfadmin.common.enums.SupplyCardStatus;
import com.decent.ejfadmin.finance.service.SupplyFinanceService;
import com.decent.ejfadmin.order.dao.OrderDao;
import com.decent.ejfadmin.order.service.OrderService;
import com.decent.ejfadmin.order.service.SupplyCardOrderService;
import com.decent.ejfadmin.product.service.PriceService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 价格检测
 *
 * @author hejunlei
 */
@SuppressWarnings("StringBufferMayBeStringBuilder")
@Service("OrderService")
public class OrderServiceImpl implements OrderService {
    private static final Logger LOGGER = LoggerFactory.getLogger(OrderServiceImpl.class);
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private SupplyFinanceService supplyFinanceService;
    @Autowired
    private PriceService priceService;
    @Autowired
    private SupplyCardOrderService supplyCardOrderService;
    @Autowired
    private CollectCardDetailService collectCardDetailService;
    /**
     * 更新销卡订单状态
     *
     * @param orderId      订单号
     * @param userId       会员id
     * @param status       订单状态
     * @param settlePrice  结算金额
     * @param dbStatus     数据库原状态
     * @param preJudgeFace 预判金额  (未用到)
     * @param failReason   停售原因/结算成功，可空
     * @return 更新行数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int modifySupplyOrder(String orderId, Long userId, Integer status, BigDecimal
            settlePrice, Integer dbStatus, BigDecimal preJudgeFace, String failReason) {
        //查询销卡订单信息
        SupplyCard card = orderDao.querySupplyOrderByOrderId(orderId);
        //实际销卡金额
        BigDecimal actualPrice;
        //成功订单
        if (status.equals(1)) {
            actualPrice = settlePrice.compareTo(card.getFace()) < 0 ? settlePrice : card.getFace();
        } else {
            //失败订单（0）
            actualPrice = settlePrice;
        }
        card.setUserPrice(priceService.getUserPriceInCallBack(status, card, actualPrice));
        int row;
        if (card.getStatus().equals(SupplyCardStatus.fail.getStatus())
                && status.equals(SupplyCardStatus.success.getStatus())) {
            //补结算订单
            row = orderDao.makeUpSupplyOrder(orderId, actualPrice, card.getUserPrice().doubleValue());
        } else {
            failReason = SupplyCardError.getFailReason(failReason);
            row = orderDao.modifySupplyOrder(orderId, status,
                    actualPrice.compareTo(BigDecimal.ZERO) == 0 ? null : actualPrice.doubleValue(), dbStatus,
                    failReason, card.getUserPrice().doubleValue(), preJudgeFace);
        }
        //订单修改失败
        if (row != 1) {
            LOGGER.info("回调修改订单状态返回row:[{}],卡信息[{}]", row, card);
            return 0;
        }

        //修改用户金额
        if (status.equals(1)) {
            SupplyConsumption supplyConsumption =
                    new SupplyConsumption(userId, SupplyConsumption.SETTLE_TYPE, card.getOrderId(),
                            null, card.getUserPrice().multiply(actualPrice), 0);

            supplyFinanceService.modifyBalanceConsumption(supplyConsumption);
        }
        //预判不符慢速试充结算处理
        supplyCardOrderService.specialDealJudgeWrongFaceCard(card.getOrderId(), settlePrice);
        return 1;
    }

    /**
     * 收卡明细查询同步功能,查询需要同步的订单
     *
     * @param ids ID
     * @return
     */
    @Override
    public List<SupplyCard> querySynchronousCard(String ids) {
        return orderDao.querySynchronousCard(ids);
    }

    /**
     * @param card       卡
     * @param resultAttr
     * @param state      销卡状态
     * @param dbStatus   数据库状态
     */
    @Override
    public void exkQueryDeal(SupplyCard card, String[] resultAttr, Integer state, Integer dbStatus) {
        ExkSupplyCard exkSupplyCard = new ExkSupplyCard();
        exkSupplyCard.setOrderId(card.getOrderId());
        exkSupplyCard.setUserId(card.getUserId());
        exkSupplyCard.setStatus(state);
        exkSupplyCard.setFace(new BigDecimal(resultAttr[3]));
        exkSupplyCard.setDbStatus(dbStatus);
        exkSupplyCard.setJudgeFace(new BigDecimal(resultAttr[7]));
        exkSupplyCard.setFailReason(resultAttr[5]);
        Integer resultLength = 12;
        if (resultAttr.length == resultLength) {
            exkSupplyCard.setAgentNo(resultAttr[9]);
            exkSupplyCard.setMobileNo(resultAttr[10]);
            String cost = resultAttr[11];
            if (StringUtils.isNotBlank(cost) && new BigDecimal(cost).compareTo(BigDecimal.ZERO) >= 0) {
                exkSupplyCard.setCost(new BigDecimal(cost));
            }
        }
        int error = modifySupplyOrderAdvance(exkSupplyCard);
        //可售且修改成功
        if (error > 0 && state != 0) {
            collectCardDetailService.orderAsyn(exkSupplyCard.getOrderId());
        }
    }
    /**
     * 更新销卡订单状态（增加了号的成本，手机号与商户编号，以计算利润）
     *
     * @param orderId    订单号
     * @param userId     会员id
     * @param status     订单状态
     * @param face       结算金额
     * @param failReason 停售原因/成功结算，可空
     * @param agentNo    易销卡的商户编号，用以区分易销卡的不同订单来源
     * @param mobileNo   该卡号对应的充值手机号码
     * @param cost       号码的成本，对应的是userPrice
     * @return 更新行数
     */
    @SuppressWarnings("JavadocReference")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int modifySupplyOrderAdvance(ExkSupplyCard exkSupplyCard) {
        Integer status = exkSupplyCard.getStatus();
        int result = modifySupplyOrder(exkSupplyCard.getOrderId(), exkSupplyCard.getUserId(), status, exkSupplyCard.getFace(),
                exkSupplyCard.getDbStatus(), exkSupplyCard.getJudgeFace(), exkSupplyCard.getFailReason());
        //若修改成功则进行增加其他订单信息
        if (result == 1) {
            //查询销卡订单信息
            if (Integer.valueOf(1).equals(status)) {
                SupplyCard card = orderDao.querySupplyOrderByOrderId(exkSupplyCard.getOrderId());
                BigDecimal userUploadFace = card.getFace();
                BigDecimal callBackFace = exkSupplyCard.getFace();
                if (callBackFace.compareTo(userUploadFace) < 0) {
                    Optional.ofNullable(exkSupplyCard.getCost()).ifPresent(cost ->
                    {
                        //计算实际卡的售价
                        BigDecimal actualSales = cost.multiply(callBackFace).divide(userUploadFace, 4, BigDecimal.ROUND_HALF_UP);
                        exkSupplyCard.setCost(actualSales);
                    });
                }
            }
            ExkSupplyCard updateRecord = new ExkSupplyCard();
            updateRecord.setOrderId(exkSupplyCard.getOrderId());
            updateRecord.setCost(exkSupplyCard.getCost());
            updateRecord.setAgentNo(exkSupplyCard.getAgentNo());
            updateRecord.setMobileNo(exkSupplyCard.getMobileNo());
            updateRecord.setEndTime(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            updateRecord.setJudgeFace(exkSupplyCard.getJudgeFace());
            orderDao.modifyExkSupplyOrder(updateRecord);
            return result;
        }
        return 0;
    }
}
